package studio.raptor.ddal.dashboard.service.impl;

import org.codehaus.plexus.util.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import studio.raptor.ddal.dashboard.log.bo.SqlProcessLogExtendData;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/1/25.
 */
public class LogSqlProcessSpecification implements Specification<SqlProcessLogExtendData> {
    private Date acceptBeginTime;
    private Date acceptEndTime;
    private String appName;
    private String sqlType;
    private Long processTime;
    private String success;

    public LogSqlProcessSpecification(Date acceptBeginTime,Date acceptEndTime,String appName,String sqlType,Long processTime,String success){
        this.acceptBeginTime=acceptBeginTime;
        this.acceptEndTime=acceptEndTime;
        this.appName=appName;
        this.sqlType=sqlType;
        this.processTime=processTime;
        this.success=success;
    }
    public Predicate toPredicate(Root<SqlProcessLogExtendData> root, CriteriaQuery<?> query, CriteriaBuilder cb){
        List<Predicate> predicate = new ArrayList<>();
        if (acceptBeginTime != null && acceptEndTime!=null) {
            predicate.add(cb.between(root.get("acceptTime").as(Date.class),acceptBeginTime,acceptEndTime));
        }
        if (StringUtils.isNotEmpty(appName)) {
            predicate.add(cb.equal(root.get("appName").as(String.class),appName));
        }
        if (StringUtils.isNotEmpty(sqlType)) {
            predicate.add(cb.equal(root.get("sqlType").as(String.class),sqlType));
        }
        if (StringUtils.isNotEmpty(success)) {
            predicate.add(cb.equal(root.get("sucess").as(String.class), success));
        }
        if (processTime!=null && processTime.longValue()!=0l) {
            predicate.add(cb.ge(root.get("processTime").as(Long.class), processTime));
        }
        Predicate[] pre = new Predicate[predicate.size()];
        return query.where(predicate.toArray(pre)).getRestriction();
    }
}
